﻿using System;
using System.Xml;

namespace Graphe
{
    public class Document
    {

        public string Name { get; set; }
        public string IndexFileName { get; set; }
        public DocumentImageCollection Images { get; set; }
        public IndexItemCollection IndexItems { get; set; }

        public void Load(string path)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(path + IndexFileName);

            Images = new DocumentImageCollection();
            IndexItems = new IndexItemCollection();

            XmlNode indexItemsNode = doc.DocumentElement.SelectSingleNode("Items");

            if (indexItemsNode != null)
            {
                foreach (XmlNode node in indexItemsNode.ChildNodes)
                {
                    IndexItem item = new IndexItem();

                    XmlNode nameNode = node.SelectSingleNode("Name");
                    XmlNode imageNumberNode = node.SelectSingleNode("ImageNumber");

                    if (nameNode != null)
                        item.Name = nameNode.InnerText;

                    if (imageNumberNode != null)
                        item.ImageNumber = Convert.ToInt32(imageNumberNode.InnerText);

                    IndexItems.Add(item);
                }
            }

            XmlNode imageReferencesNode = doc.DocumentElement.SelectSingleNode("ImageReferences");
            if (imageReferencesNode != null)
            {
                foreach (XmlNode imageNode in imageReferencesNode.ChildNodes)
                {
                    DocumentImage image = new DocumentImage(imageNode.Attributes["FileName"].Value);
                    image.ManuscriptName = Name;

                    if (imageNode.Attributes["Number"] != null)
                    {
                        int imageNumber = 0;
                        bool isInt = Int32.TryParse(imageNode.Attributes["Number"].Value, out imageNumber);

                        image.ImageNumber = imageNumber;
                    }

                    Images.Add(image);
                }
            }
        }

        public DocumentImage FindImage(int imageNumber)
        {
            foreach (DocumentImage image in Images)
            {
                if (image.ImageNumber == imageNumber)
                    return image;
            }

            return null;
        }
    }
}
